package org.mayuanxiaonong.timserver.pack.config;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.mayuanxiaonong.timserver.config.SystemConfig;
import org.mayuanxiaonong.timserver.pack.msgpack.IPack;
import org.mayuanxiaonong.timserver.util.ConfigException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MessagePack报文协议配置
 * 
 * @author 9527
 *
 */
public class MessagePackConfig extends PackConfig<Integer, IPack> {

	private static final Logger log = LoggerFactory
			.getLogger(MessagePackConfig.class);
	private static MessagePackConfig instance = null;

	private MessagePackConfig() {
		super();
	}

	public static MessagePackConfig getInstance() {
		if (instance == null) {
			synchronized (MessagePackConfig.class) {
				if (instance == null) {
					instance = new MessagePackConfig();
				}
			}
		}
		return instance;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void load() {
		File file = new File(SystemConfig.getInstance().getConfDir(),
				"pack/msgpack.xml");
		if (!file.exists()) {
			throw new ConfigException("报文协议配置文件不存在," + file.getAbsolutePath());
		}
		log.info("加载MessagePack报文协议配置文件," + file.getAbsolutePath());
		SAXReader reader = new SAXReader();
		Document doc = null;
		try {
			doc = reader.read(file);
		} catch (DocumentException e) {
			throw new ConfigException("dom4j读取配置文件失败", e);
		}
		List<Element> elements = doc.selectNodes("/msgpack/bean");
		for (Element element : elements) {
			String beanName = element.attributeValue("class");
			Class<?> beanClass = null;
			try {
				beanClass = Class.forName(beanName);
			} catch (ClassNotFoundException e) {
				throw new ConfigException("报文协议类不存在," + beanName, e);
			}
			try {
				IPack pack = (IPack) beanClass.newInstance();
				super.putPack(pack.getVersion(), pack);
			} catch (InstantiationException | IllegalAccessException e) {
				throw new ConfigException("生成报文协议类代理对象出错," + beanName, e);
			}
		}
		log.info("加载MessagePack报文协议配置文件结束");
	}

}
